﻿using System;
using System.Collections.Generic;
using System.Text;
using DBUtil.SqlSegment;

namespace DBUtil.Provider.SqlServer.SqlSegment
{
    /// <summary>
    /// SqlServer中的日期时间运算符
    /// </summary>
    public class SqlServerDateTimeSqlSegment : DateTimeSqlSegment
    {
        public SqlServerDateTimeSqlSegment(DBAccess db) : base(db)
        {
        }

        public override string DefaultDateTimeType => "datetime2";
        public override string Current => "getdate()";

        #region 当前时间加上 年/月/天/小时/分钟/秒
        public override string GetCurrentAddYear(int year) => $"dateadd(year,{year},getdate())";
        public override string GetCurrentAddMonth(int month) => $"dateadd(month,{month},getdate())";
        public override string GetCurrentAddDay(int day) => $"dateadd(day,{day},getdate())";
        public override string GetCurrentAddHour(int hour) => $"dateadd(hour,{hour},getdate())";
        public override string GetCurrentAddMinute(int minute) => $"dateadd(minute,{minute},getdate())";
        public override string GetCurrentAddSecond(int second) => $"dateadd(second,{second},getdate())";
        #endregion

        public override string GetStringInSql(DateTime datetime) => $"'{datetime.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
        public override string GetFilterString(string colName, DateTime? start, DateTime? end, bool includeStart = true, bool includeEnd = false)
        {
            if (start == null && end == null) return "";
            var filterSql = "";
            if (start != null)
            {
                filterSql += $"{colName} {(includeStart ? ">=" : ">")}'{start.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
            }
            if (end != null)
            {
                filterSql += $"{colName} {(includeEnd ? "<=" : "<")}'{end.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
            }
            return filterSql;
        }
    }
}
